package com.jia;

import sun.reflect.generics.tree.Tree;

/**
 * @program: Leetcode
 * @description:
 * @author: STU756
 * @create: 2020-08-07 01:50
 */
public class Test1 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode l1 = new TreeNode(2);
        TreeNode r1 = new TreeNode(3);
        TreeNode l2 = new TreeNode(4);
        TreeNode r2 = new TreeNode(5);
        root.left = l1;
        root.right = r1;
        r1.left = l2;
        r1.right = r2;
        Test1 test1 = new Test1();
        String serialize = test1.serialize(root);
        System.out.println();
        test1.deserialize(serialize);
    }

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null) return "null";
        return root.val + "," + serialize(root.left) + "," + serialize(root.right);
    }

    private String data;
    public TreeNode deserialize(String data) {
        this.data = data;
        return deserialize();
    }
    // Decodes your encoded data to tree.
    public TreeNode deserialize() {
        if(data.length() == 0) return null;
        int index = data.indexOf(",");
        String numStr = (index == -1)? data : data.substring(0, index);
        if(numStr.equals("null")) {
            return null;
        }
        data = (index == -1)? "" : data.substring(index+1);
        TreeNode root = new TreeNode(Integer.parseInt(numStr));
        root.left = deserialize(data);
        root.right = deserialize(data);
        return root;
    }
    static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode(int val) {
            this.val = val;
        }
    }
}
